package 树;
/**
 * https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/
 */
public class _114_二叉树展开为链表 {
    public class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode() {}
       TreeNode(int val) { this.val = val; }
       TreeNode(int val, TreeNode left, TreeNode right) {
           this.val = val;
           this.left = left;
           this.right = right;
       }
    }

    //函数定义:将当前root为根节点的二叉树拉成一个链表
    public void flatten(TreeNode root) {
        if(root == null) return;


        //将当前二叉树的左右子树都拉成一个链表
        flatten(root.left);
        flatten(root.right);

        TreeNode left = root.left; //左子树记录
        TreeNode right = root.right; //右子树记录

        root.left = null; //断开左子树
        root.right = left; //将右子树替换成左子树

        TreeNode tmp = root;
        //迭代找到右子树最后一个节点，将以前的右子树接上
        while(tmp.right!=null){
            tmp = tmp.right;
        }
        tmp.right = right;
    }
}
